package com.authine.cloudpivot.engine.service.bizrule.handler;

import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.domain.runtime.BizObject;
import com.authine.cloudpivot.engine.enums.status.DataRowStatus;
import com.authine.cloudpivot.engine.open.service.OpenEngine;
import com.authine.cloudpivot.engine.service.bizrule.handler.context.Request;

import okhttp3.OkHttpClient;
import okhttp3.Response;

public class 工作日同步 extends BaseHandler {
    private static final Logger LOG = LoggerFactory.getLogger("在线编码-节假日同步-年度节假日");
    private static final String URL = "https://api.apihubs.cn";
    private static final String YEAR_KEY = "year";
    private static final Integer SIZE = 380;

    @Override
    public Object handle(Request request) {
        OpenEngine engine = this.getOpenEngine(request);
        BizObject bizObject = request.getData().getBizObject();
        /* 获取年份 */
        Object obj = bizObject.getData().get(YEAR_KEY);
        if (obj instanceof Timestamp) {
            /* 拼接URL */
            Integer year = ((Timestamp) obj).toLocalDateTime().getYear();
            StringBuffer sb = new StringBuffer(URL).append("/holiday/get?size=").append(SIZE).append("&field=date,workday").append("&year=").append(year);

            DateTimeFormatter inf = DateTimeFormatter.ofPattern("yyyyMMdd");
            DateTimeFormatter outf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            try (Response response = client.newCall(new okhttp3.Request.Builder().url(sb.toString()).get().build()).execute()) {
                JSONObject data = JSON.parseObject(response.body().string());
                bizObject.getData().put("sync_code", data.getInteger("code"));
                bizObject.getData().put("sync_msg", data.getString("msg"));
                if (data.getInteger("code") == 0) {
                    /* 获取信息成功 解析并填充数据 */
                    JSONArray dates = data.getJSONObject("data").getJSONArray("list");
                    List<Map<String, Object>> details = new ArrayList<>();
                    dates.stream().map(o -> (JSONObject) o).forEach(item -> {
                        Map<String, Object> temp = new HashMap<>();
                        temp.put(BizObject.DATAROWSTATUS, DataRowStatus.Modified);
                        temp.put("id", "customid" + item.getString("date"));
                        temp.put("jjrq", LocalDate.parse(item.getString("date"), inf).format(outf));
                        temp.put("sfgzr", item.getInteger("workday") == 1 ? true : false);
                        details.add(temp);
                    });
                    bizObject.getData().put("workday_details", details);
                    LOG.info("===>>获取{}全年日历信息成功 返回数据：{}", year, dates);
                } else {
                    LOG.warn("===>>获取{}全年日历信息失败 返回信息：{}", year, data.get("msg"));
                }
            } catch (IOException e) {
                LOG.error("===>>请求全年日历出错 URL：{} 错误信息：{}", sb, e.getLocalizedMessage());
            }
        }
        engine.updateBizObject(bizObject, true);
        return bizObject;
    }
}
